<template>
  <div class="app-container">
    <el-input
      v-model="listQuery.sociaty_no"
      placeholder="请输入工会号"
      style="width: 200px"
      clearable
    ></el-input>
    <el-input
      v-model="listQuery.search"
      placeholder="请输入工会名称"
      style="width: 200px"
      clearable
    ></el-input>
    <el-select filterable v-model="listQuery.status" placeholder="请选择状态">
      <el-option
        v-for="item in optionsStatus"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
    <el-select filterable v-model="listQuery.type" placeholder="请选择类别">
      <el-option
        v-for="item in optionsLevel"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
    <el-button type="primary" @click="searchList" icon="el-icon-search">搜索</el-button>

    <!--    <div class="filter-container" style="margin-top:10px;">-->
    <el-button
      class="filter-item"
      type="primary"
      icon="el-icon-plus"
      @click="handleCreate()">
      添加
    </el-button>
    <!--    </div>-->

    <el-table
      :data="menuList"
      style="margin-bottom: 20px; margin-top: 10px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="sociaty_no" label="工会号"></el-table-column>
      <el-table-column prop="sociaty_name" label="工会名称"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="add_time" label="创建时间"></el-table-column>
      <el-table-column prop="avatar" label="工会头像">
        <template slot-scope="scope">
          <el-popover placement="right" width="420" trigger="hover">
            <img
              :src="scope.row.avatar"
              alt=""
              style="max-width: 400px; max-height: 400px"
            />
            <img
              slot="reference"
              :src="scope.row.avatar"
              alt=""
              style="width: 50px; height: 50px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="parent_name" label="父级名称"></el-table-column>
      <el-table-column prop="admin_id" label="admin_id"></el-table-column>
      <el-table-column prop="type" label="类别">
        <template slot-scope="scope">
          {{ scope.row.type === 1 ? "工会" : "" }}
          {{ scope.row.type === 2 ? "厅" : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="relations" label="关系">
        <template slot-scope="scope">
          {{ scope.row.relations === 0 ? "未挂靠" : "" }}
          {{ scope.row.relations === 1 ? "直属" : "" }}
          {{ scope.row.relations === 2 ? "挂靠" : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? "正常" : "" }}
          {{ scope.row.status === 2 ? "封禁" : "" }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="user_id" label="用户ID"> </el-table-column> -->
      <el-table-column prop="user_code" label="用户ID"></el-table-column>

      <el-table-column prop="room_id" label="房间编号"></el-table-column>
      <el-table-column prop="toplimit" label="直属厅上限"></el-table-column>
      <el-table-column min-width="420" label="操作">
        <template slot-scope="scope">
          <!--          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>-->
          <!--            编辑-->
          <!--          </el-button>-->
          <el-button
            type="primary"
            size="mini"
            @click="getDetail(scope.row)"
            plain
          >工会详情
          </el-button
          >
          <el-button
            v-if="scope.row.type === 1"
            type="primary"
            size="mini"
            @click="dismiss(scope.row)"
            plain
          >解散工会
          </el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="setToplimit(scope.row)"
            plain
            v-if="scope.row.type === 1"
          >直属厅上限
          </el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="showUpdateNum(scope.row)"
            plain
          >修改工会号
          </el-button
          >
          <!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />
    <!--    v-show="total>0"-->

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="工会名称" prop="sociaty_name">
          <el-input
            v-model="form.sociaty_name"
            placeholder="工会名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="工会描述">
          <el-input
            v-model="form.description"
            placeholder="工会描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="工会号" prop="sociaty_no">
          <el-input v-model="form.sociaty_no" placeholder="工会号(6位数字)"/>
        </el-form-item>
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="form.user_id" placeholder="用户ID"/>
        </el-form-item>
        <el-form-item label="工会logo" prop="avatar">
          <span>{{ form.avatar ? form.avatar.name : "" }}</span>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <!-- 修改工会号 -->
    <el-dialog
      v-dialogDrag
      title="修改工会号"
      :visible.sync="dialogFormVisible5"
      @close="handleDialogClose5">
      <el-form
        ref="dataForm5"
        :rules="rules5"
        :model="form5"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto">
        <el-form-item label="工会编号" prop="sociaty_no">
          <el-input v-model="form5.sociaty_no" placeholder="工会编号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible5 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm5()">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="工会详情"
      :visible.sync="dialogFormVisible2"
      @close="handleDialogClose2"
    >
      <el-form
        :model="form2"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="管理员姓名：">{{ form2.admin_name }}</el-form-item>
        <el-form-item label="管理员账号：">{{ form2.admin_account }}</el-form-item>
        <el-form-item label="初始密码："
        >{{ form2.password }}（密码仅第一次有效）
        </el-form-item
        >
        <el-form-item label="工会登录地址："
        ><a
          :href="form2.sociaty_url"
          target="_blank"
          style="color: #7badff; white-space: nowrap"
        >{{ form2.sociaty_url }}</a
        >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="dialogFormVisible2 = false">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      title="编辑工会直属厅上限"
      :visible.sync="dialogFormVisible3"
      @close="handleDialogClose3"
    >
      <el-form
        ref="dataForm3"
        :model="form3"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="上限数值" prop="limit">
          <el-input-number
            v-model="form3.limit"
            :min="1"
            label="上限数值"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible3 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm3()">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      title="工会详情"
      :visible.sync="dialogFormVisible4"
      @close="handleDialogClose4"
    >
      <el-form
        :model="form4"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="工会名称：">{{ form4.sociaty_name }}</el-form-item>
        <el-form-item label="工会号：">{{ form4.sociaty_no }}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="dialogFormVisible4 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm4()"> 解散</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveMenu,
  deleteMenu,
  treeMenu,
  updateMenu,
  cacheMenu,
  getDetail,
  setToplimit,
  dismiss,
  updateNum,
} from "@/api/union2/union";

import treeTable from "@/components/TreeTable";
import {validateCh} from "@/utils/validate";

// 常量title
const tempDesc = {
  id: "",
  parentId: "",
  menu_key: "菜单key值",
  menu_name: "名称",
  level: "排序",
  icon: "图标",
  type: "类型",
  status: "状态",
  parent_id: "上级菜单",
};
export default {
  components: {treeTable},
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error("不能包含中文"));
      }
      callback();
    };
    return {
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: "展开全部",
      tempDesc: tempDesc,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
      },
      columns: [
        {
          label: "菜单名称",
          key: "title",
          width: 220,
          expand: true,
          align: "left",
          headerAlign: "center",
        },
        {
          label: "菜单key值",
          key: "menu_key",
        },
        {
          label: tempDesc.type,
          key: "type",
        },
        {
          label: "状态",
          key: "status",
        },
        {
          label: tempDesc.icon,
          key: "icon",
        },
        {
          label: "菜单层级",
          key: "level",
        },
      ],
      menuList: [],
      menuTree: [], // 树形菜单
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      dialogFormVisible5: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加",
      },
      form: {
        sociaty_name: undefined,
        description: undefined,
        sociaty_no: undefined,
        user_id: undefined,
        avatar: undefined,
      },
      form2: {
        admin_name: undefined,
        admin_account: undefined,
        password: undefined,
        sociaty_url: undefined,
      },
      form3: {
        sociaty_id: undefined,
        limit: undefined,
      },

      form4: {
        admin_name: undefined,
        admin_account: undefined,
      },
      //  * @apiParam {number} id 列表sociaty_id,必传
      //  * @apiParam {number} type 分类,必传
      //  * @apiParam {number} sociaty_no 工会编号,必传
      form5: {
        id: undefined,
        type: undefined,
        sociaty_no: undefined,
      },
      optionsStatus: [
        {value: undefined, label: "全部状态"},
        {value: "1", label: "正常"},
        {value: "2", label: "封禁"},
      ],
      optionsLevel: [
        {value: undefined, label: "全部类别"},
        {value: "1", label: "工会"},
        {value: "2", label: "厅"},
      ],
      rules: {
        sociaty_name: [
          {required: true, message: "请输入工会名称", trigger: "blur"},
        ],
        sociaty_no: [
          {required: true, message: "请输入工会号", trigger: "blur"},
          {len: 6, message: "工会号必须为6位", trigger: "blur"},
        ],
        user_id: [{required: true, message: "请输入用户ID", trigger: "blur"}],
        avatar: [
          {required: true, message: "请输入工会logo", trigger: "blur"},
        ],
      },
      rules3: {
        limit: [{required: true, message: "请输入上限次数", trigger: "blur"}],
      },
      rules5: {
        sociaty_no: [
          {required: true, message: "请输入工会号", trigger: "blur"},
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 点击查询
    searchSubmit() {
      this.listQuery.page = 1;
      this.getList()
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`;
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`;
      }
      if (this.listQuery.sociaty_no) {
        urlData = urlData + `&sociaty_no=${this.listQuery.sociaty_no}`;
      }
      if (this.listQuery.type) {
        urlData = urlData + `&type=${this.listQuery.type}`;
      }

      treeMenu(urlData).then((response) => {
        this.menuList = response.data.list;
        this.total = response.data.meta.total;
        this.listLoading = false;
      });
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    getDetail(row) {
      // this.dialogFormVisible = true
      let that = this;
      getDetail(row.sociaty_id).then((response) => {
        that.form2 = response.data;
        that.dialogFormVisible2 = true;
      });
    },
    //     admin_id: 16
    // avatar: "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f8272846f3c4.jpg"
    // memo: (...)
    // parent_id: (...)
    // parent_name: (...)
    // relations: (...)
    // room_rate: (...)
    // sociaty_id: (...)
    // sociaty_name: (...)
    // sociaty_no: (...)
    // status: (...)
    // toplimit: (...)
    // type: 2
    // user_id: (...)
    // user_rate: (...)
    // 回显数据
    showUpdateNum(row) {
      this.dialogFormVisible5 = true;
      this.form5.type = row.type;
      this.form5.id = row.sociaty_id;
      this.form5.sociaty_no = row.sociaty_no;
    },
    searchList() {

    },
    // 提交修改工会号
    submitForm5() {
      // this.form.parent_id = undefined;
      this.$refs["dataForm5"].validate((valid) => {
        if (!valid) {
          return;
        }
        let formData = new FormData();
        for (let item in this.form5) {
          this.form5[item] === undefined
            ? ""
            : formData.append(item, this.form5[item]);
        }
        updateNum(formData).then((response) => {
          if (response.code === 200) {
            this.getList();
            this.$notify({
              type: 'success',
              message: '操作成功',
              position: 'bottom-right',
              showClose: false,
              duration: 3000
            });
            ;
            this.dialogFormVisible5 = false;
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            });
            ;
          }
        });
      });
    },
    setToplimit(row) {
      this.dialogFormVisible3 = true;
      this.form3.sociaty_id = row.sociaty_id;
      this.form3.limit = row.toplimit;
    },
    dismiss(row) {
      this.dialogFormVisible4 = true;
      this.form4.sociaty_name = row.sociaty_name;
      this.form4.sociaty_no = row.sociaty_no;
      this.form4.sociaty_id = row.sociaty_id;
    },
    handleUpdate(row) {
      this.form = [];
      // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
      this.form.sociaty_name = row.sociaty_name;
      this.form.description = row.description;
      this.form.sociaty_no = row.sociaty_no;
      this.form.user_id = row.user_id;
      this.form.avatar = row.avatar;

      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      let parentNode = this.findTreeNode(row.parentId);
      if (parentNode) {
        this.form.parent_id = parentNode.menu_name;
      }

      this.form = Object.assign({}, this.form);
    },
    handleDelete(row) {
      deleteMenu(row.id).then((response) => {
        if (response.code === 0) {
          this.getList();
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
          ;
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
          ;
        }
      });
    },
    submitForm() {
      // this.form.parent_id = undefined;
      this.$refs["dataForm"].validate((valid) => {
        let formData = new FormData();
        for (let item in this.form) {
          this.form[item] === undefined
            ? ""
            : formData.append(item, this.form[item]);
        }
        if (valid && this.dialogStatus === "create") {
          saveMenu(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              ;
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
              ;
            }
          });
        } else if (valid && this.dialogStatus === "update") {
          updateMenu(formData).then((response) => {
            if (response.code === 200) {
              this.getList();
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              ;
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
              ;
            }
          });
        }
      });
    },
    submitForm3() {
      // this.form.parent_id = undefined;
      this.$refs["dataForm3"].validate((valid) => {
        let formData = new FormData();
        for (let item in this.form3) {
          this.form3[item] === undefined
            ? ""
            : formData.append(item, this.form3[item]);
        }
        setToplimit(formData).then((response) => {
          if (response.code === 200) {
            this.getList();
            this.$notify({
              type: 'success',
              message: '操作成功',
              position: 'bottom-right',
              showClose: false,
              duration: 3000
            });
            ;
            this.dialogFormVisible3 = false;
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            });
            ;
          }
        });
      });
    },
    submitForm4() {
      let formData = {sociaty_id: this.form4.sociaty_id};
      dismiss(formData).then((response) => {
        if (response.code === 200) {
          this.getList();
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
          ;
          this.dialogFormVisible4 = false;
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
          ;
        }
      });
    },
    cache() {
      cacheMenu(this.form).then((response) => {
        this.$notify({
          type: 'success',
          message: '操作成功',
          position: 'bottom-right',
          showClose: false,
          duration: 3000
        });
        ;
      });
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, {id: parseInt(id)});
      return node;
    },
    handleExpand() {
      this.expandAll = !this.expandAll;
      this.expandAllTitle = this.expandAll ? "折叠全部" : "展开全部";
    },
    resetForm() {
      this.form = {
        sociaty_name: undefined,
        description: undefined,
        sociaty_no: undefined,
        user_id: undefined,
        avatar: undefined,
      };
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
    handleDialogClose2() {
    },
    handleDialogClose3() {
    },
    handleDialogClose4() {
    },
    handleDialogClose5() {
    },
    handleAvatarSuccess(res, file) {
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      this.form.avatar = file;
    },
  },
};
</script>
